package com.gin.no_gay_alliance.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.gin.jackson.utils.ObjectUtils;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.databinding.ActivityMainBinding;
import com.gin.no_gay_alliance.fragment.main.MainConfigFragment;
import com.gin.no_gay_alliance.fragment.main.MainDailyFragment;
import com.gin.no_gay_alliance.fragment.main.MainHomeFragment;
import com.gin.no_gay_alliance.fragment.main.MainNoticeFragment;
import com.gin.no_gay_alliance.fragment.user.UserCenterFragment;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.BuglyUtils;
import com.gin.no_gay_alliance.utils.ClipboardUtils;
import com.gin.no_gay_alliance.utils.HandlerMessage;
import com.gin.no_gay_alliance.utils.PermissionUtils;
import com.gin.no_gay_alliance.utils.UrlUtils;
import com.google.android.material.navigation.NavigationBarView;

public class MainActivity extends BaseBindingActivity<ActivityMainBinding> implements NavigationBarView.OnItemSelectedListener {
    private UserCenterFragment userCenterFragment;
    private MainNoticeFragment mainNoticeFragment;

    /**
     * 解析意图
     *
     * @param intent 意图
     */
    @Override
    protected void handleIntent(Intent intent) {

    }

    /**
     * onCreate中的后续操作
     */
    @Override
    protected void onCreate() {
        //请求权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            PermissionUtils.checkPermissions(this, 0, Manifest.permission.POST_NOTIFICATIONS);
        }

        // 检查更新
        MyApplication.app.managerFactory.getUpgradeManager().checkUpgrade(this);
        // 初始化vp2
        b.vp2.setAdapter(new FragmentStateAdapter(this) {
            @NonNull
            @Override
            public Fragment createFragment(int position) {
                switch (position) {
                    case 0:
                        long userId = MyApplication.getClient().getUserId();
                        userCenterFragment = UserCenterFragment.getInstance(userId);
                        return userCenterFragment;
                    case 1:
                        return new MainHomeFragment();
                    case 2:
                        return new MainDailyFragment();
                    case 3:
                        mainNoticeFragment = new MainNoticeFragment();
                        return mainNoticeFragment;
                    case 4:
                        return new MainConfigFragment();
                    default:
                        throw new RuntimeException("没有那个Fragment");
                }
            }

            @Override
            public int getItemCount() {
                return 5;
            }
        });

        //设置初始位置
        setSelected(1);


        // 禁用ViewPager2的左右滑动，只允许通过点击导航按钮切换
        b.vp2.setUserInputEnabled(false);

        // 点击导航按钮时，同步切换ViewPager2的页面
        b.bottomNavi.setOnItemSelectedListener(this);

        //bugly请求授权
        BuglyUtils.buglyConfirm(this);
    }

    /**
     * 装载右上角菜单
     *
     * @param menu         菜单
     * @param menuInflater 菜单渲染器
     */
    @Override
    protected void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {

    }

    /**
     * 处理消息
     *
     * @param message 消息
     * @return 是否消耗该消息
     */
    @Override
    public boolean handleMessage(@NonNull Message message) {
        if (message.what == HandlerMessage.UPDATE_CURRENT_USER_ID) {
            // 更新当前用户id
            long userId = (long) message.obj;
            Log.d(TAG, "更新当前用户id: " + userId);

            // 用户中心
            if (userCenterFragment != null) {
                userCenterFragment.setUserId(userId);
            }
        }

        return super.handleMessage(message);
    }

    /**
     * 如果布局中直接有toolbar, 在此提供, 如果使用Fragment布局中的toolbar,Fragment渲染完成后调用 setToolbar 方法装载
     *
     * @return toolbar toolbar
     */
    @Override
    protected Toolbar initToolbar() {
        return b.toolbar;
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 检查剪贴板 如果发现nga链接，提示使用本app打开
        uiDelayed(this::checkUrl, 200);

    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        // 提醒
        if (item.getItemId() == R.id.menu_item_noti) {
            NoticeActivity.startActivity(this);
            return true;
        }
        // 私信
        if (item.getItemId() == R.id.menu_item_pm) {
            PriMsgActivity.startActivity(this);
            return true;
        }
        // 历史
        if (item.getItemId() == R.id.menu_item_topic_history) {
            TopicHistoryActivity.startActivity(this);
            return true;
        }
        // 举报记录
        if (item.getItemId() == R.id.menu_item_reporting_record) {
            ReportingRecordActivity.startActivity(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 底部导航栏菜单的点击回调
     *
     * @param item 导航栏菜单项
     * @return boolean
     */
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if (R.id.navigation_me == itemId) {
            b.vp2.setCurrentItem(0, false);
        }
        if (R.id.navigation_home == itemId) {
            b.vp2.setCurrentItem(1, false);
        }
        if (R.id.navigation_daily == itemId) {
            b.vp2.setCurrentItem(2, false);
        }
        if (R.id.navigation_notifications == itemId) {
            b.vp2.setCurrentItem(3, false);
        }
        if (R.id.navigation_config == itemId) {
            b.vp2.setCurrentItem(4, false);
        }
        toolbar.setTitle(item.getTitle());
        return true;
    }

    /**
     * 检查剪贴板 如果发现nga链接，提示使用本app打开
     */
    private void checkUrl() {
        String text = ClipboardUtils.getText(0);
        if (!ObjectUtils.isEmpty(text) && UrlUtils.isOpenableUrl(text)) {
            Log.d(getClass().getSimpleName(), "发现站内链接: " + text);

            AlertDialog alertDialog = AlertDialogUtils.showConfirm(this, "发现站内链接", "发现剪贴板内的站内链接, 是否打开: " + text, (dialog, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    UrlUtils.openUrl(text, MainActivity.this);
                }
                // 点击任意按钮清空剪贴板
                ClipboardUtils.clear();
            });
            alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setText("清除");
        }
    }

    /**
     * 设置选中标签
     *
     * @param index 序号
     */
    private void setSelected(int index) {
        b.vp2.setCurrentItem(index, false);
        b.bottomNavi.getMenu().getItem(index).setChecked(true);
    }
}